import { type GoGoAST } from "gogocode";
import {
  CommonParams,
  I18nConfig,
  IGoGoCodeNode,
  IGoGoNodeAttr,
  ILogger,
} from "../types";
import { genKey, updateLocalesFile } from "../utils/file";
import { hasChinese, isChinese } from "../utils/check";

const parseTemplate = ({
  sfcAst,
  CONFIG,
  logger,
  filePath,
}: CommonParams & { sfcAst: GoGoAST }): GoGoAST => {
  const { I18N_FUNC, CHINESE_REGEX: CRG } = CONFIG;
  const getKey = (text: string) =>
    updateLocalesFile({
      text,
      CONFIG,
      logger,
      filePath,
    });
  return sfcAst
    .find(`<template></template>`)
    .find(`<$_$ $$$0>$$$1</$_$>`)
    .each((item) => {
      // 获取子节点
      const children = item.match["$$$1"] as unknown as IGoGoCodeNode[];
      // 处理子节点
      children.forEach(({ nodeType, content: { value } }) => {
        const originText = value?.content || "";
        if (
          nodeType === "text" &&
          value &&
          originText.trim() !== "" &&
          hasChinese(originText, CRG)
        ) {
          if (originText.includes("{{") && originText.includes("}}")) {
            const REG = new RegExp(`(\\'|\\")([\\w${CRG}]+)\\1`);
            let tempStr = originText;
            const strList: string[] = [];
            while (tempStr.length) {
              const matched = [...tempStr.matchAll(/\{\{[\s\S]+?\}\}/g)];
              if (matched.length === 0) {
                strList.push(tempStr);
                break;
              }
              const match = matched?.[0];
              if (match && match[0]) {
                const prev = tempStr.slice(0, match.index);
                if (prev) {
                  strList.push(prev);
                }
                strList.push(match[0]);
                tempStr = tempStr.slice(match.index + match[0].length);
              }
            }
            value.content = strList.reduce((prev, str) => {
              if (hasChinese(str, CRG)) {
                if (str.startsWith("{{") && str.endsWith("}}")) {
                  return (prev += str.replace(REG, (_, p1, p2) => {
                    const key = getKey(p2.trim());
                    return `${I18N_FUNC}('${key}')`;
                  }));
                } else {
                  const key = getKey(str.trim());
                  return (prev += `{{ ${I18N_FUNC}('${key}') }}`);
                }
              }
              return (prev += str);
            }, "");
          } else {
            const noSpaceText = originText.trim();
            const REG =
              noSpaceText.length === 1
                ? new RegExp(`[\\w${CRG}]`)
                : new RegExp(`[\\w${CRG}][\\w${CRG} ]*[\\w${CRG}]`);
            const tempStr = originText.replace(REG, (match) => {
              const key = getKey(match);
              return `{{ ${I18N_FUNC}('${key}') }}`;
            });
            value.content = tempStr;
          }
        }
      });
      // 处理属性
      const attrs = item.match["$$$0"] as unknown as IGoGoNodeAttr[];
      attrs.forEach((attr) => {
        const { key, value } = attr;
        if (hasChinese(value.content)) {
          const prop = key.content;
          const val = value.content;
          if (
            prop.startsWith("v-") ||
            prop.startsWith(":") ||
            prop.startsWith("@")
          ) {
            if (hasChinese(val)) {
              const REG = new RegExp(`(\\'|\\")([\\w${CRG}]+)\\1`);
              value.content = val
                .replace(REG, (match, p1, p2) => {
                  console.log("🚀 ~ value.content=val.replace ~ p2:", p2);
                  const keyVal = genKey(p2);
                  return `${CONFIG.I18N_FUNC}('${keyVal}')`;
                })
                .replace(/(\`)([\S\s]+?)\1/, (match, p1, p2: string) => {
                  const obj: Record<string, unknown> = {};
                  const str = p2.replace(/\$\{([\S\s]+?)\}/g, (m, p1, p2) => {
                    obj[p1] = p1;
                    return `{${p1}}`;
                  });
                  const key = genKey(str);
                  return `${CONFIG.I18N_FUNC}('${key}',{${Object.keys(obj).join(",")}})`;
                });
            }
          } else {
            const keyVal = genKey(val);
            value.content = `${CONFIG.I18N_FUNC}('${keyVal}')`;
            key.content = `:${prop}`;
          }
        }
      });
    })
    .root();
};

export default parseTemplate;
